-- DragonPredictionM
-- created by huanghr
-- 大预言术

module("DragonPredictionM", package.seeall);

local PredictionInfo = {};
local skillTypes = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    PredictionInfo = {};
    skillTypes = {};

    -- 转换下dragon_prediction_CSV信息表
    local prediction_CSV = get_dragon_prediction_CSV();
    for i = 1, #prediction_CSV do
        local row = prediction_CSV[i];
        PredictionInfo[row.id] = row;

        -- 区分下类型
        if skillTypes[row.skill_type] == nil  then
            skillTypes[row.skill_type] = {};
            table.insert(skillTypes[row.skill_type], row.id);
        else
            table.insert(skillTypes[row.skill_type], row.id);
        end
    end
end

-- 模块初始化操作
function init()
    loadCsv();
end

function query(id, path)
    local m = PredictionInfo[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 通过类型获得技能ID
function getSkillIdsByType(skillType)
    return skillTypes[skillType];
end

-- 获得所有技能类型
function getAllSkillType()
    return table.keys(skillTypes);
end

-- 通过时技能ID获得对应ID
function getIdBySkillId(skillId)
    for k, value in pairs(PredictionInfo) do
        if value.skill_id == skillId then
            return value.id;
        end
    end

    return -1;
end

-- 施放大预言术技能
function castPredictionSkill(pos, skillId)
    local arr = ME.user.dbase:queryTemp("dragon_pre_skills", {});
    if arr[1] ~= skillId then
        return;
    end

    table.remove(arr, 1);

    local targetPos = pos;
    if SkillM.needTarget(skillId) and not isMonster(targetPos) then
        targetPos = getTargetPos();
    end

    -- 没有目标
    if targetPos == -1 then
        tryFireCombatRound(arr);
        return true;
    end

    SkillM.cast(ME.user, skillId, targetPos);
    tryFireCombatRound(arr);
    return true;
end

-- 尝试抛出事件
function tryFireCombatRound(arr)
    if #arr > 0 then
        return;
    end

    -- 触发完了，抛事件
    EventMgr.fire(event.COMBAT_ROUND, { ["pos"] = -1, ["isDelay"] = true, });
end

-- 当前位子是怪物
function isMonster(pos)
    local grid = DungeonM.getGridByPos(pos);
    local monster = grid.monster;

    if  grid:isOpened() and monster and not monster:isDead() then
        return true;
    end

    return false;
end

-- 随机找一个怪物的位置
function getTargetPos()
    local arr = SkillM.getTargets(TARGET_TYPE_RANDOM);
    local pos = -1;
    if #arr > 0 then
       pos = arr[1]:getPos();
    end

    return pos;
end